package handlers

import (
	"elec-stat-mgr/cache"
	"elec-stat-mgr/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Shop{}).Count(&count)

	var shop []models.Shop

	redis_key := "list_shop" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"count": count,
		"shop":  shop,
	})
	return
}
func Comment(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	shopId, _ := strconv.Atoi(c.PostForm("shop_id"))
	content := c.PostForm("content")

	comment := models.Comment{
		Content: content,
		UserID:  userId,
		ShopID:  shopId,
	}
	err := models.DB.Create(&comment).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论添加失败",
		})
		return
	}

	var shop models.Shop
	err = models.DB.Where("id = ?", shopId).First(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}

	shop.CommentCount++
	err = models.DB.Save(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}
